package com.cosc.apgs.param.interceptor;


import com.cosc.apgs.param.annotation.TokenCheck;
import com.cosc.apgs.param.token.TokenUtil;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * 拦截器方法，重写了预处理方法，该方法会对token进行校验
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {

        //判断请求是否是调用控制器方法，不是的话直接返回
        if (!(object instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        //检查方法是否有TokenCheck注解，有的话就校验token
        if (method.isAnnotationPresent(TokenCheck.class)) {

            TokenCheck tokenCheck = method.getAnnotation(TokenCheck.class);

            if (tokenCheck.required()) {

                //从http请求头里获取token对象
                String token = httpServletRequest.getHeader("token");
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无法获取token信息，请重新登录！");
                }
                // 验证 token
                TokenUtil.checkToken(token);
            }
        }
        return true;
    }

}
